# app.py
from fastapi import FastAPI, File, UploadFile, HTTPException, Request, Depends

from pydantic import BaseModel
from typing import Optional
import tempfile
import os

from src.dependencies.auth import verify_token
from src.middleware.auth import auth_middleware
from src.utils.idcard_ocr import IDCardOCR
from src.config import settings

# 在app.py中添加
from fastapi.middleware.cors import CORSMiddleware
from src.utils.response import error_response, success_response

# 使用 os.getenv 获取配置
# EASYOCR_GPU = os.getenv('EASYOCR_GPU', 'False').lower() == 'true'
# 忽略GPU缺失警告
import warnings
warnings.filterwarnings("ignore", message="Neither CUDA nor MPS are available")
app = FastAPI( root_path=settings.ROOT_PATH,docs_url=settings.DOCS_URL,openapi_url=settings.OPENAPI_URL , redoc_url=settings.REDOC_URL,debug=settings.DEBUG,title=settings.APP_NAME, description=settings.APP_DESCRIPTION)

app.middleware("http")(auth_middleware)  # 全局注册中间件
origins = [
    "http://localhost",
    "http://localhost:3000",  # 前端域名
]
# 解决跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
ocr = IDCardOCR()


class RecognitionResult(BaseModel):
    """识别结果模型"""
    name: Optional[str] = None
    gender: Optional[str] = None
    ethnicity: Optional[str] = None
    birth_date: Optional[str] = None
    address: Optional[str] = None
    id_number: Optional[str] = None
    issuing_authority: Optional[str] = None
    valid_period: Optional[str] = None
    error: Optional[str] = None


@app.post("/ocr/idcard/{side}", dependencies=[Depends(verify_token)])
async def recognize_idcard(side: str, file: UploadFile = File(...)):
    if side not in ["front", "back"]:
        return {"error": "无效的side参数，必须为front或back"}

    # 保存临时文件
    with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp:
        temp_path = temp.name
        contents = await file.read()
        temp.write(contents)

    try:
        # 确保文件已关闭且可访问
        result = ocr.recognize(temp_path, side)

        # 处理OCR结果
        if isinstance(result, dict):
            if "error" in result:
                return error_response(code=500, msg=result["error"])
            return success_response(data=result)

        else:
            return error_response(code=500, msg="未知错误")

    except Exception as e:
        return error_response(code=500, msg=str(e))

    finally:
        # 确保在所有情况下都删除临时文件
        if os.path.exists(temp_path):
            os.unlink(temp_path)# 清理临时文件

async def _process_idcard_ocr(file: UploadFile, card_side: str) -> dict:
    """处理身份证OCR识别的通用逻辑"""
    # 验证文件类型
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="上传的文件不是图片")

    # 创建临时文件
    with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as temp:
        temp_path = temp.name
        # 写入上传的文件内容
        contents = await file.read()
        temp.write(contents)

    try:
        # 调用OCR识别
        result = ocr.recognize(temp_path, card_side)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"识别出错: {str(e)}")
    finally:
        # 删除临时文件
        os.unlink(temp_path)


# 将配置挂载到app.state上
@app.on_event("startup")
def startup_event():
    app.state.config = settings

# 在路由中使用
# @app.get("/")
# def root(request: Request):
#     config = request.app.state.config
#     return {"host": config.SERVER_HOST}
@app.get("/", tags=["文档"])
async def get_docs(request: Request):
    config = request.app.state.config
    """获取API文档"""
    return {"message": "欢迎使用身份证OCR识别API，请访问/docs查看文档"}